<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form
            size="small"
            :model="queryData"
            layout="inline"
            v-if="permissionStore.hasPermisson('jqsbwh.cx')"
          >
            <a-form-item label="公司名称">
              <a-cascader
                :options="pageData.corporateList"
                v-model="queryData.firmId"
                allow-clear
                class="bacClass"
                :loading="pageData.corporateLoading"
                popup-container="html"
              />
            </a-form-item>
            <a-form-item label="机台编号">
              <!-- <a-select popup-container="html"  class="bacClass" v-model="queryData.jitai" :style="{ width: '200px' }"
                              :allowClear="true" :filter-option="false" @click="jitaiCx" allow-search @search="jitaiCxs">
                              <a-option v-for="item in queryData.jitais">
                                  {{ item.machineCode }}
                              </a-option>
                          </a-select> -->
              <a-input
                class="bacClass"
                v-model="queryData.jitai"
                @press-enter="huiche"
                allow-clear
                style="width: 200px"
              ></a-input>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="pageData.btnList"
            @select="selectHandler"
            @add="addHandler"
            @del="delWeipaichan"
            @export="exports"
            @enable="enables"
            @deactivate="deactivates"
            style="float: right"
          ></Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <!-- <div class="my-tool-bar">
                  
              </div> -->
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: calc(100% - 45px)"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
        @columnResized="onColumnResized"
        @columnMoved="onColumnMoved"
      ></AgGridVuesCopys>
      <paginationCopys
        :page-size="pagination.pageSize"
        :current="pagination.page"
        :total="total"
        show-total
        show-jumper
        show-page-size
        @change="PageSize"
        @page-size-change="change1"
        style="justify-content: center"
      />
      <!-- </a-tab-pane>
              </a-tabs> -->
    </template>

    <a-drawer
      :style="{ zIndex: 999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="formData" layout="horizontal">
          <a-form-item label-col-flex="80px" field="numberId" label="唯一编号">
            <a-input class="bacClass" v-model="formData.numberId" disabled></a-input>
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            field="coordinate"
            label="位置号"
            :rules="[{ required: true, message: '位置号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="formData.coordinate" disabled></a-input>
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            field="machineTypeName"
            label="机台类型"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClayarn buildss" v-model="formData.machineTypeName" disabled />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            field="machineCode"
            label="机台编号"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="formData.machineCode" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            field="machineName"
            label="机台名称"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="formData.machineName" />
          </a-form-item>
          <!--          <a-form-item label-col-flex="80px" field="machineTypeName" label="机台类型" :validate-trigger="['change', 'blur']">-->
          <!--            &lt;!&ndash; <a-input class="bacClass" v-model="formData.machineTypeName" /> &ndash;&gt;-->
          <!--            <a-select popup-container="html"   class="bacClass" v-model="formData.machineTypeName"  placeholder="请填写机台类型">-->
          <!--            <a-option v-for="item in typeNameList" :value="item.typeName" :label="item.typeName" />-->
          <!--            </a-select>-->
          <!--          </a-form-item>-->
          <a-form-item label-col-flex="80px" field="obsoleteState" label="是否停机">
            <span style="width: 20px"></span>
            <a-switch v-model="formData.obsoleteState" :checked-value="1" :unchecked-value="0">
              <template #checked> 是 </template>
              <template #unchecked> 否 </template>
            </a-switch>
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            field="areaName"
            label="所属区域"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="formData.areaName" disabled />
          </a-form-item>
          <a-form-item label-col-flex="80px" field="remark" label="备注">
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="formData.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <a-modal
      v-model:visible="visible"
      title="二维码"
      ok-text="关闭"
      @ok="gbModal"
      :closable="false"
      :hide-cancel="true"
      :mask-closable="false"
    >
      <a-space direction="vertical">
        <a-button type="primary" @click="print">打印</a-button>
        <div id="machinery" style="width: 400px">
          <QrcodeVue :value="qrData.code"></QrcodeVue>
          <div style="display: inline-block; vertical-align: top; margin-left: 15px">
            <!-- qrData.firm = record.firm;
                              qrData.jtCode = record.machineCode;
                              qrData.jtName = record.machineName;
                              qrData.jtType = record.machineTypeName;
                              qrData.jtXy = record.coordinate;
                              qrData.jtFimli = record.areaName; -->
            <div style="width: 200px">公司:{{ qrData.firm }}</div>
            <div style="width: 200px">机台编号:{{ qrData.jtCode }}</div>
            <div style="width: 200px">机台名称:{{ qrData.jtName }}</div>
            <div style="width: 200px">机台类别:{{ qrData.jtType }}</div>
            <div style="width: 200px">所属区域:{{ qrData.jtFimli }}</div>
          </div>
        </div>
      </a-space>
    </a-modal>
  </pageTabelLayout>
</template>

<script setup lang="ts">
  import axios from 'axios'
  import { onMounted, reactive, ref } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import {
    useTableColumn,
    useTable,
    usePagination,
    useRowSelection,
    useRowKey,
  } from '@/hooks/table'
  import { post, get } from '@/api/http'
  import { Message, Modal } from '@arco-design/web-vue'
  import ModalDialog from '@/components/ModalDialog.vue'
  import QrcodeVue from 'qrcode.vue'
  import printJS from 'print-js'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import WHService from '@/service/wh'
  
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import usePermission from '@/store/modules/permission'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

  import { slicing } from '@/utils/caseFrimAndSecRig'
  const whService = new WHService()
  const companyList = whService.companyList
  const localeText1: any = ref(localeText)
  const pagingList1: any = ref(pagingList)
  const visible = ref(false)
  //定义TS类型
  interface Firm {
    name: string
    id: number
  }

  interface Cloth {
    code: string
  }

  interface MachineType {
    id: number | string
    code: string
    name: string
    maxCapacity: string
    //删除
    deleteState: number | string | undefined
    // 作废的状态
    obsoleteState: number | string | undefined
  }

  interface Machine {
    id: string
    serialNo: number
    code: string
    name: string
    machineTypeId: any
    machineTypeName: string
    // coordinate: string;
    areaId: any
    areaName: string
  }

  const rowKey = useRowKey('id')

  interface gcTsObj {
    code: string
    company: string
    createDate: string
    createUser: string
    id: number
    isActive: boolean
    remark: any
    sortIndex: number
    updateDate: string
    updateUser: string
  }

  const gbModal = () => {
    visible.value = false
  }

  // 变动机台名称
  const changeName = () => {
    window.setTimeout(() => {
      formData.machineName = formData.machineCode + '/' + formData.machineTypeName
    }, 100)
  }
  const total = ref(10)
  const page = ref(1)
  const size = ref(10)
  function PageSize(val: any) {
    pagination.page = val
    doRefresh()
  }

  function change1(val: any) {
    pagination.pageSize = val
    doRefresh()
  }
  //下拉框查询
  // function selCxAll() {
  //   post({
  //     url: 'org/firmGroup/getFirmInfoByMap',
  //     data: {
  //       firmName: '',
  //       department: '',
  //     },
  //   }).then((result) => {
  //     if (result.code === 200) {
  //       if (result.data.length == 0) {
  //         queryData.gcList = []
  //         gsDatas.value = []
  //       } else {
  //         queryData.gcList = result.data
  //         gsDatas.value = result.data
  //       }
  //     }
  //   })
  // }

  const qrData = reactive({
    id: 0,
    firm: '',
    jtCode: '',
    jtName: '',
    jtType: '',
    jtXy: '',
    jtFimli: '',
    code: '',
  })

  //生成条码
  const GenerateBtn = (record: any) => {
    qrData.firm = record.firm
    qrData.jtCode = record.machineCode
    qrData.jtName = record.machineName
    qrData.jtType = record.machineTypeName
    // qrData.jtXy = record.coordinate;
    qrData.jtFimli = record.areaName
    // qrData.code = JSON.stringify({
    //   // id: record.id,
    //   // firm: encodeURI(record.firm),
    //   // machineName: encodeURI(record.machineName),
    //   machineCode: record.machineCode,
    //   // machineTypeName: encodeURI(record.machineTypeName),
    //   // coordinate: encodeURI(record.coordinate),
    //   // areaName: encodeURI(record.areaName),
    // })
    qrData.code = record.machineCode

    visible.value = true
  }

  const print = () => {
    printJS({
      printable: 'machinery',
      type: 'html',
      targetStyles: ['*'],
    })
  }

  let gc = reactive<gcTsObj[]>([])
  gc = JSON.parse(localStorage.getItem('gc') || '{}')

  //查询表单form和select绑定的数据
  const queryData: any = reactive({
    firm: '',
    gcList: [],
    jitai: '',
    jitais: [],
  })

  //机台类别form和select绑定的数据
  const typeData = reactive({
    types: '',
  })

  //所属区域form和select绑定的数据
  const areaData = reactive({
    areas: '',
  })

  //下拉框和弹窗的数据变量
  const pageData = reactive<{
    gcList: Firm[]
    //暂时，需要等后台返回的数据类型，再看定义ts
    typeList: any[]
    areaList: any[]
    nameList: any[]
    showAdd: boolean
    sideTitle: string
    codeValue: string
    showQrcode: boolean
    corporateList: any[]
    btnList: any[]

    corporateId: string
    corporateLoading: boolean
  }>({
    //选择工厂下拉框数据
    gcList: [],
    //机台类别的下拉框数据
    typeList: [],
    //所属区域的下拉框数据
    areaList: [],
    nameList: [],
    //弹窗是否显示
    showAdd: false,
    //弹窗的标题
    sideTitle: '新增类型',
    //通过机台类型和机台名称动态生成二维码-动态绑定的数据变量
    codeValue: '',
    btnList: [],
    //是否显示和隐藏二维码的弹窗
    showQrcode: false,
    corporateList: [],
    corporateId: '',
    corporateLoading: false,
  })

  let gsDatas = ref<any[]>([])
  const headerShow = ref<boolean>(true)
  onMounted(() => {
    getCorporateList()
    // selCxAll()
  })
  const typeNameList = ref<any>([])
  //修改
  const editHandler = (record: any) => {
    //发起分页查询的请求
    post({
      url: 'planSingle/machineType/getMachineTypePara',
      data: {},
    }).then((result: any) => {
      //如果后台返回的状态码为200才能执行后续操作
      if (result.code === 200) {
        typeNameList.value = result.data
      }
    })
    //数据回填
    for (let key in record) {
      formData[key] = record[key]
    }
    if (formData.machineNum == null || formData.machineNum == undefined) {
      formData.machineNum = 0
    }
    // formData.id = Number(record.id)
    // formData.firm = record.firm
    // formData.machineCode = record.machineCode;
    // formData.machineName = record.machineName;
    //机台类别名称
    formData.machineTypeName = record.machineTypeName
    formData.firmId = record.firmId
    formData.firm = record.firm
    formData.machineTypeId = record.machineTypeId
    //机台坐标
    // formData.coordinate = record.coordinate;
    //机台区域名称
    formData.areaName = record.areaName
    formData.areaId = record.areaName
    formData.remark = record.remark
    //显示弹窗
    pageData.showAdd = true

    //弹窗的标题
    pageData.sideTitle = '修改机器设备维护'
  }
  // 停用
  const deactivates = () => {
    if (gridOption.value.getSelectedRows().length == 0) {
      Message.error('请勾选数据')
      return false
    }
    if (gridOption.value.getSelectedRows().some((item: any) => item.machineState !== 1)) {
      Message.error('只能选择待单的数据')
      return
    }
    Modal.confirm({
      title: '系统提示',
      content: '是否停用？',
      onOk() {
        post({
          url: 'planSingle/machine/saveNotUse',
          data: gridOption.value.getSelectedRows().map((res: any) => {
            return res.id
          }),
        }).then((res: any) => {
          if (res.code === 200) {
            doRefresh()
            Message.success('停用成功')
          } else {
            Message.error(res.message)
          }
        })
      },
    })
  }
  const enables = () => {
    if (gridOption.value.getSelectedRows().length == 0) {
      Message.error('请勾选数据')
      return false
    }
    if (gridOption.value.getSelectedRows().some((item: any) => item.machineState !== 0)) {
      Message.error('只能选择未启用的数据')
      return
    }
    Modal.confirm({
      title: '系统提示',
      content: '是否启用？',
      onOk() {
        post({
          url: '/planSingle/machine/saveUse',
          data: gridOption.value.getSelectedRows().map((res: any) => {
            return res.id
          }),
        }).then((res: any) => {
          if (res.code === 200) {
            doRefresh()
            Message.success('启用通过')
          } else {
            Message.error(res.message)
          }
        })
      },
    })
  }

  //表格的列描述信息|
  const columns = useTableColumn([
    // {
    //   title: '序号',
    //   // 列信息的标识，对应表格的数据
    //   dataIndex: 'serialNo',
    //   key: 'serialNo',
    //   width: 150,
    // },
    {
      title: '公司名称',
      dataIndex: 'firm',
      key: 'firm',
      width: 150,
    },
    {
      title: '固定资产编号',
      dataIndex: 'numberId',
      key: 'numberId',
      width: 150,
    },
    {
      title: '机台编号',
      dataIndex: 'machineCode',
      width: 150,
      key: 'machineCode',
    },
    {
      title: '机台名称',
      dataIndex: 'machineName',
      width: 150,
      key: 'machineName',
    },
    {
      title: '设备机型',
      dataIndex: 'machineTypeName',
      key: 'machineTypeName',
      width: 150,
    },
    {
      title: '位置号',
      dataIndex: 'coordinate',
      width: 150,
      key: 'coordinate',
    },
    {
      title: '所属区域',
      dataIndex: 'areaName',
      width: 150,
      key: 'areaName',
    },
    // {
    //   title: '机器产能',
    //   dataIndex: 'machineNum',
    //   width: 150,
    //   key: 'machineNum',
    // },
    {
      title: '是否停机',
      dataIndex: 'obsoleteState',
      width: 150,
      key: 'obsoleteState',
      slotName: 'obsoleteState',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
      key: 'remark',
    },
    {
      title: '创建人',
      dataIndex: 'createName',
      width: 150,
      key: 'createName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 200,
      key: 'createTime',
    },
    {
      title: '修改人',
      dataIndex: 'updateName',
      width: 150,
      key: 'updateName',
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      width: 200,
      key: 'updateTime',
    },
    {
      title: '机台状态',
      slotName: 'machineState',
      width: 200,
      key: 'machineState',
      fixed: 'right',
    },
    {
      title: '生成条码',
      slotName: 'Barcode',
      width: 100,
      key: 'barcode',
      fixed: 'right',
    },
    {
      title: '操作',
      slotName: 'Operation',
      width: 150,
      key: 'operation',
      fixed: 'right',
    },
  ])

  let tc: any[] = columns.map((o) => {
    let obj = {
      headerName: o.title,
      field: o.key,
      pinned: o['fixed'],
      tooltipField: o.key,
    }

    if (o.slotName === 'obsoleteState') {
      obj['resizable'] = false
      obj['filter'] = true
      obj['filterParams'] = {
        valueFormatter: function (params) {
          return params.value == 0 ? '否' : params.value == 1 ? '是' : ''
        },
      }
      obj['sortable'] = false
      // obj["lockPosition"] = "right"

      obj['cellRenderer'] = {
        template: `<span>{{a}}</span>`,
        setup(props: any) {
          return {
            a: props.params.data.obsoleteState == 0 ? '否' : '是',
          }
        },
      }
    }

    if (o.slotName === 'machineState') {
      obj['resizable'] = false
      obj['filter'] = true
      obj['filterParams'] = {
        valueFormatter: function (params) {
          return params.value == 0
            ? '未启动'
            : params.value == 1
            ? '待单'
            : params.value == 2
            ? '待纱'
            : params.value == 3
            ? '洗转机'
            : params.value == 4
            ? '运行'
            : params.value == 5
            ? '暂停'
            : params.value == 6
            ? '维修'
            : params.value == 7
            ? '保养'
            : '停用'
        },
      }
      obj['sortable'] = false
      // obj["lockPosition"] = "right"

      obj['cellRenderer'] = {
        template: `<span>{{a}}</span>`,
        setup(props: any) {
          return {
            a:
              props.params.data.machineState == 0
                ? '未启动'
                : props.params.data.machineState == 1
                ? '待单'
                : props.params.data.machineState == 2
                ? '待纱'
                : props.params.data.machineState == 3
                ? '洗转机'
                : props.params.data.machineState == 4
                ? '运行'
                : props.params.data.machineState == 5
                ? '暂停'
                : props.params.data.machineState == 6
                ? '维修'
                : props.params.data.machineState == 7
                ? '维修'
                : '停用',
          }
        },
      }
    }

    if (o.slotName === 'Barcode') {
      obj['resizable'] = false
      obj['filter'] = false
      obj['sortable'] = false
      // obj["lockPosition"] = "right"

      obj['cellRenderer'] = {
        template: `<a-tag color="green" style="cursor:pointer" @click="a">生成条码</a-tag>`,
        setup(props: any) {
          const a = () => {
            GenerateBtn(props.params.data)
          }
          return {
            a,
          }
        },
      }
    }

    if (o.slotName === 'Operation') {
      obj['resizable'] = false
      obj['filter'] = false
      obj['sortable'] = false
      obj['lockPosition'] = 'right'
      obj['width'] = '100px'
      obj['cellRenderer'] = {
        template: `<el-button style="color:#165dff;"  type="info" link  v-if="isEdit"  @click="a">修改</el-button>`,
        setup(props: any) {
          const a = () => {
            editHandler(props.params.data)
          }
          let isEdit = permissionStore.hasPermisson('jqsbwh.xg')
          return {
            a,
            isEdit,
          }
        },
      }
    }

    return obj
  })

  let a = [
    {
      showRowGroup: 'hide_def',
      headerName: '',
      checkboxSelection: true,
      headerCheckboxSelection: true,
      pinned: 'left',
      width: 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: 'left',
    },
  ]
  tc = a.concat(tc)

  //新增修改弹窗动态绑定的数据
  let formData: any = reactive({
    id: 0,
    machineCode: '',
    machineName: '',
    firm: '',
    machineTypeName: '',
    machineTypeId: 0,
    areaName: '',
    remark: '',
    areaId: 0,
    machineNum: 0,
    coordinate: '',
    firmId: '',
    obsoleteState: 0,
    numberId: '',
  })

  //复选框选中的值
  const { selectedRowKeys } = useRowSelection()

  //此方法用于表格数据动态渲染
  const table = useTable()

  //表格的pagination分页的属性配置
  const pagination = usePagination(doRefresh)

  function doRefresh() {
    //发起分页查询的请求
    post({
      url: 'planSingle/machine/getMachinePage',
      data: {
        page: pagination.page,
        size: pagination.pageSize,
        machineCode: queryData.jitai,
        firmId: queryData.firmId,
      },
    }).then((result: any) => {
      //如果后台返回的状态码为200才能执行后续操作
      if (result.code === 200) {
        //将后台返回的分页查询数据传入，这个方法可获取表格的数据dataList,动态渲染表格，表格的data属性动态绑定table.dataList即可实现动态渲染
        table.handleSuccess(result.data.list)
        //result.data.pages：总页数
        //使用这个方法，可以将pagination总页数pageCount改为-当前用户点击查询后台返回的总页数
        //传入完成之后，即可动态绑定表格渲染
        // pagination.setTotalSize(result.data.total);
        gridOption.value.setRowData(result.data.list)
        total.value = result.data.total
      }
    })
  }

  //查询
  const selectHandler = () => {
    pagination.page = 1
    doRefresh()
  }

  // //导出的封装的方法
  // function tableToXlsx(table: any, filename: any) {
  //     const uri = 'data:application/vnd.ms-excel;base64,',
  //         template = `<html>
  //             <head><meta charset="UTF-8"></head>
  //             <body><table border="1">${table.innerHTML}</table></body>
  //         </html>`;

  //     const a = document.createElement('a');
  //     a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
  //     a.download = filename;
  //     a.click();
  //     // document.removeChild(a);
  // }

  // //导出
  // const prints = () => {
  //     Modal.confirm({
  //         title: '系统提示',
  //         content: '是否导出列表数据',
  //         onOk() {
  //             let table = document.getElementsByTagName("table")[1]
  //             tableToXlsx(table, '机器设备维护')

  //         }
  //     })
  // }
  const exports = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
      Message.error('请先勾选')
      return
    } else {
      //将表头拼接出来
      let head =
        '<th>公司名称</th><th>机台编号</th><th>机台名称</th><th>机台类别</th><th>所属区域</th><th>备注</th><th>创建人</th><th>创建时间</th><th>修改人</th><th>修改人时间</th>'
      //拿到当前表格数据与勾选的行做筛选

      let nowRow = table.dataList.filter(function (o) {
        return (
          gridOption.value
            .getSelectedRows()
            .map((o: any) => {
              return o.id
            })
            .indexOf(o['id']) !== -1
        )
      })
      let body = ''
      nowRow.forEach(function (o) {
        body += '<tr><td>' + o['firm'] + '</td>'
        body += '<td>' + o['machineCode'] + '</td>'
        body += '<td>' + o['machineName'] + '</td>'
        body += '<td>' + o['machineTypeName'] + '</td>'
        body += '<td>' + o['areaName'] + '</td>'
        body += '<td>' + o['remark'] + '</td>'
        body += '<td>' + o['createName'] + '</td>'
        body += '<td>' + o['createTime'] + '</td>'
        body += '<td>' + o['updateName'] + '</td>'
        body += '<td>' + o['updateTime'] + '</td>'
        body += '</tr>'
      })
      tableToXlsx(head, '机器设备维护', body)
    }
  }
  const corporateRef = ref<any>()
  const corporateChange = (event: any) => {
    formData.areaName = ''
    nextTick(() => {
      formData.firm = corporateRef.value.selectViewValue[0].label
    })
  }
  // 获取公司列表
  const getCorporateList = async () => {
    try {
      pageData.corporateLoading = true
      const res = await post({ url: 'org/baCompany/getTreeCompanyByUser' })
      if (res.code == 200) {
        pageData.corporateList = res.data
        return
      }
      Message.error(res.message)
    } catch (error: any) {
      pageData.corporateLoading = false
    } finally {
      pageData.corporateLoading = false
    }
  }
  function tableToXlsx(head: any, filename: any, body: any) {
    const uri = 'data:application/vnd.ms-excel;base64,',
      template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

    const a = document.createElement('a')
    a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
    a.download = filename
    a.click()
    document.removeChild(a)
  }

  // 表格准备事件
  const gridOption = ref()
  const colState = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
  }

  //表格的弹窗的确认和取消
  const formRef = ref<FormInstance>()
  const sideOk = () => {
    formRef.value?.validate().then((err) => {
      if (!err) {
        let id1 = 0
        pageData.typeList.forEach((item: any) => {
          if (item.typeName == formData.machineTypeName) {
            id1 = item.id
          }
        })
        let id2 = 0
        pageData.areaList.forEach((item: any) => {
          if (item.areaName == formData.areaName) {
            id2 = item.id
          }
        })
        if (formData.machineNum == null || formData.machineNum == undefined) {
          formData.machineNum = 0
        }
        if (pageData.sideTitle === '新增机器设备维护') {
          if (formData.machineNum == null || formData.machineNum == undefined) {
            formData.machineNum = 0
          }
          post({
            url: 'planSingle/machine/addMachine',
            data: [
              {
                id: null,
                firm: formData.firm,
                firmId: formData.firmId,
                machineName: formData.machineName,
                machineCode: formData.machineCode,
                machineTypeId: id1,
                machineTypeName: formData.machineTypeName,
                // coordinate: formData.coordinate,
                areaId: id2,
                areaName: formData.areaName,
                remark: formData.remark,
                machineNum: formData.machineNum,
                coordinate: formData.coordinate,
                obsoleteState: formData.obsoleteState,
              },
            ],
          }).then((res: any) => {
            if (res.code === 200) {
              pageData.showAdd = false
              doRefresh()
              //提示
              Message.success('新增成功')
            } else Message.error(res.message)
          })
        } else {
          if (id1 != undefined) {
            formData.machineTypeId = Number(id1)
          }
          if (id2 != undefined) {
            formData['areaId'] = Number(id2)
          }
          post({
            url: 'planSingle/machine/updateMachine',
            data: [formData],
          }).then((res: any) => {
            if (res.code === 200) {
              doRefresh()
              pageData.showAdd = false
              Message.success('修改成功')
            } else {
              Message.error(res.message)
            }
          })
        }
      }
    })
  }

  //新增
  const addHandler = () => {
    for (let item in formData) {
      formData[item] = ''
    }
    if (formData.machineNum == null || formData.machineNum == undefined) {
      formData.machineNum = 0
    }
    pageData.showAdd = true
    pageData.sideTitle = '新增机器设备维护'
  }

  const inputBlur1 = () => {
    formData.machineCode = formData.machineCode.toUpperCase()
  }

  //删除
  const delWeipaichan = () => {
    // if (selectedRowKeys.value.length === 0) {
    //     Message.error('请先勾选')
    //     return
    // }
    if (gridOption.value.getSelectedRows() === 0) {
      Message.error('请先勾选')
      return
    }
    const isArray = selectedRowKeys.value.map((num) => {
      return Number(num)
    })

    Modal.confirm({
      title: '系统提示',
      content: '确认删除选中的数据?',
      onOk() {
        //删除的请求
        post({
          url: 'planSingle/machine/delMachine',
          // data: isArray
          data: gridOption.value.getSelectedRows().map((o: any) => {
            return o.id
          }),
        }).then((res: any) => {
          if (res.code === 200) {
            Message.success({
              content: '删除成功',
              duration: 5000,
            })
            pagination.page = 1
            doRefresh()
          } else {
            Message.error({
              content: res.message,
              duration: 5000,
            })
          }
        })
      },
    })
  }
  //下拉框得到焦点
  const focusSel1 = () => {
    selJq({ typeName: '' })
  }
  //获取下拉框的机械类别
  const options1 = ref<any>(pageData.typeList)
  const loading1 = ref(false)
  const handleSearch1 = (value: any) => {
    if (value) {
      const ob = { typeName: value }
      loading1.value = true
      selJq(ob)
      options1.value = pageData.typeList
      loading1.value = false
    } else {
      options1.value = []
    }
  }

  //获取下拉框的机械类别
  function selJq(val: any) {
    post({
      url: '/planSingle/machineType/getFieldValue',
      data: val,
    }).then((res: any) => {
      if (res.code === 200) {
        pageData.typeList = res.data
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    })
  }

  //下拉框得到焦点
  const focusSel2 = () => {
    selQy('')
  }
  //获取下拉框的机械类别
  const options2 = ref<any>(pageData.areaList)
  const loading2 = ref(false)
  const handleSearch2 = (value: any) => {
    if (value) {
      loading2.value = true
      selQy(value)
      options2.value = pageData.areaList
      loading2.value = false
    } else {
      options2.value = []
    }
  }

  //获取下拉框的机械类别
  function selQy(val: any) {
    if (formData.firmId == '' || formData.firmId == undefined || formData.firmId == null) {
      Message.warning({
        content: '请先选择公司！',
        duration: 2000,
      })
      return
    }
    //获取所属区域下拉框数据
    post({
      url: 'planSingle/machineArea/getFieldValueByFirm',
      data: {
        firmId: formData.firmId,
        firm: formData.firm,
        // areaName: val,
      },
    }).then((res: any) => {
      if (res.code === 200) {
        pageData.areaList = res.data
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    })
  }
  const handleChange = (_data: any) => {
    table.handleSuccess(_data)
  }
  const changeFirm = () => {
    formData.areaName = ''
    pageData.areaList = []
  }
  //判断是否填写了中文
  const isChiese = (value: string, cb: Function) => {
    return new Promise<void>((resolve) => {
      if (window.encodeURI(value).indexOf('%') !== -1) {
        cb('填写的值不能包含中文！')
      }
      resolve()
    })
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
  }
  const jitaiCx = () => {
    chaxuns({ machineCode: '' })
  }
  const jitaiCxs = (val: any) => {
    chaxuns({ machineCode: val })
  }
  function chaxuns(val: any) {
    post({
      url: 'planSingle/machine/getFieldValue',
      data: val,
    }).then((res: any) => {
      if (res.code == 200) {
        queryData.jitais = res.data
      }
    })
  }

  //下拉框得到焦点
  const focusSel = () => {
    selCxAll123({ locationMark: '' })
  }

  //下拉数据
  const options = ref<any>(pageData.nameList)
  const loading = ref(false)
  const handleSearch = (value: any) => {
    if (value) {
      const ob = { locationMark: value, deleteState: 0 }
      loading.value = true
      selCxAll123(ob)
      options.value = pageData.nameList
      loading.value = false
    } else {
      options.value = []
    }
  }
  //下拉框查询
  function selCxAll123(val: any) {
    post({
      url: '/planSingle/LocationMarkSet/getFieldValue',
      data: val,
    }).then(({ data, code }: any) => {
      if (code === 200) {
        console.log(data)
        let dataList: any = []
        data.forEach(function (o: any) {
          dataList.push(o['locationMark'])
        })
        pageData.nameList = dataList
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    })
  }
  const huiche = () => {
    doRefresh()
  }
  // :items="['查询', '新增', '删除', '导出']"
  const permissionStore = usePermission()
  if (permissionStore.hasPermisson('jqsbwh.cx')) {
    pageData.btnList.push('查询')
    pageData.btnList.push('启用')
    pageData.btnList.push('停用')
  }
  // if (permissionStore.hasPermisson('jqsbwh.xz')) {
  //   pageData.btnList.push('新增')
  // }
  // if (permissionStore.hasPermisson('jqsbwh.sc')) {
  //   pageData.btnList.push('删除')
  // }
  if (permissionStore.hasPermisson('jqsbwh.dc')) {
    pageData.btnList.push('导出')
  }
  const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
    saveOrUpdateGridState01('MachineryEquipment01', gridOption, colState, tc)
  const onColumnMoved = () => {
    saveGridState01()
  }
  const onColumnResized = () => {
    saveGridState01()
  }
</script>

<style scoped lang="less">
  #select {
    background-color: white;
    border: 1px solid black;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-cell.ag-cell-first-right-pinned:not(.ag-cell-range-left):not(.ag-cell-range-single-cell)) {
    text-align: center;
  }
</style>
